import asyncio
import websockets
import json
import threading

# 每一个epoch的模型准确率结果数组
ar = [1, 2, 3, 4, 5]

# 回应前端请求
async def handle_client(websocket, path):
    client_ip = websocket.remote_address[0]
    print(f"client connected from {client_ip}")

    try:
        async for message in websocket:
            if message == 'get':
                print(client_ip + " request get")
                # 当接收到 'get' 消息时，发送 ar 变量的值
                await websocket.send(json.dumps({'ack': 1,'accuracy': ar}))
    except websockets.exceptions.ConnectionClosed:
        pass

def run_server():
    asyncio.set_event_loop(asyncio.new_event_loop())
    start_server = websockets.serve(handle_client, '0.0.0.0', 5600)
    print('websocket run at localhost:5600')
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

if __name__ == '__main__':
    server_thread = threading.Thread(target=run_server)
    server_thread.start()